package com.sam.spring.security.compent;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @classname: CustomRBACService
 * @description: TODO
 * @Author: sam
 * @date: 2021/7/14 11:26
 */
@Slf4j
@Component
public class CustomRbacService {

    /**
     * 判断是否有权限
     * @return
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication){
        // 登录认证的主体信息
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;

            String requestURI = request.getRequestURI();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(requestURI);
            log.info("请求uri:{}",requestURI);
            log.info("登录用户的权限:{}", JSONObject.toJSONString(userDetails.getAuthorities()));
            return userDetails.getAuthorities().contains(simpleGrantedAuthority);
        }
        return false;
    }
}
